package com.site.controller;

import com.mybatis.pj.example.select.multipart.MultipartSelectExample;
import com.site.common.R;
import com.site.common.annotation.AccessLimit;
import com.site.common.annotation.CurrentUser;
import com.site.common.annotation.ParamXssPass;
import com.site.common.config.TokenConfig;
import com.site.pojo.ScheduleJob;
import com.site.pojo.TestPojo;
import com.site.pojo.User;
import com.site.service.ITestService;
import com.site.common.quartz.QuartzJobManager;
import com.site.util.JwtTokenUtil;
import com.site.vo.TestFormVo;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试
 */
@RestController
public class QuartzTestController extends BaseController{

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TokenConfig tokenConfig;
    @Autowired
    private ITestService iTestService;

    @PostMapping("/testadd")
    public R testadd(@RequestBody @Valid TestFormVo testFormVo){
        return R.ok(testFormVo.buildEntity());
    }

    @GetMapping("/test")
    public R test(){
        /* 批量新增时主键id必须为自增的
        ArrayList<TestPojo> list = new ArrayList<>();
        list.add(TestPojo.builder().name("小三").build());
        list.add(TestPojo.builder().name("小四").build());
        int res = iTestService.insertBatch(list);*/
        TestPojo testPojo = new TestPojo();
        testPojo.setId(RandomUtils.nextInt(100,10000));
        testPojo.setName("小7");
        int res = iTestService.insert(testPojo);
        System.out.println("返回，"+testPojo);
        System.out.println("id，"+res);
        if (res > 0){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 多表查询(pj.mybati基于 tk.mapper 扩展了多表查询与更新)
     * @return
     */
    @GetMapping("/test_join")
    public R testJoin(){
        MultipartSelectExample multipartSelectExample = new MultipartSelectExample("tb_test","tt");
        // 定义查询返回的字段且需要在实体中进行定义该字段
        String[] lists = {"tt.id", "tt.name", "ttt.id test_table_id", "ttt.test_id"};
        multipartSelectExample.setFields(Arrays.asList(lists));
        multipartSelectExample.addLeftJoin("tb_test_table","ttt","tt.id=ttt.test_id").end();
        return R.ok(iTestService.findJoinPage(1,1,multipartSelectExample));
    }

    @GetMapping("/token")
    @AccessLimit // 限流注解
    @ParamXssPass // 过滤xss注解
    public R token(@CurrentUser User user){// 获取用户注解
        System.out.println("获取当前登录用户"+user.toString());
        JwtTokenUtil.setTokenSettings(tokenConfig);
        String subject = "1000";// 一般为用户id
        Map map = new HashMap<>();
        map.put("name","小二");
        String token = JwtTokenUtil.generateToken(subject,map);// 1
        String token1 = JwtTokenUtil.generateToken(tokenConfig.getIssuer(),subject,map,60000,tokenConfig.getSecret());// 2

        String s = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNqqVspLzE1VslJ6uqH_ya4eJR2l1IoCJStDU0tjI1NTAyMDHaXMxBKYgImlmUEtAAAA__8.RbOvOcSHBmRuK9SuzdwcqxhXbiSFuvEARx39aO29Jqg";
        boolean res = JwtTokenUtil.check(s);
        System.out.println(res);
        if (res){
            Claims claims = JwtTokenUtil.parseToken(token);
            System.out.println(claims);
        }
        return R.ok(token);
    }

    @GetMapping("/check")
    public R<String> testQuartzCheck(){
        boolean res1 = QuartzJobManager.check(100L);
        boolean res2 = QuartzJobManager.check(200L);
        boolean res3 = QuartzJobManager.check(300L);
        return R.ok("ok：验证是否存在，" + res1 + "，" + res2 + "，" + res3);
    }

    @GetMapping("/addjob")
    public R<String> testQuartzAdd() {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setBeanName("testTask");
        scheduleJob.setJobId(100L);
        scheduleJob.setStatus(0);
        scheduleJob.setParams("我是测试定时器");
        scheduleJob.setCronExpression("*/2 * * * * ?");
        scheduleJob.setRemark("测试");
        scheduleJob.setCreateTime(new Date());

        Date startTime = QuartzJobManager.createScheduleJob(scheduleJob);
        // 自定义的 schedule_job 定时任务表需要在此处添加入库，这里我就不添加了，自行扩展
        // ....
        return R.ok("ok：开始时间，" + startTime);
    }

    @GetMapping("/updatejob")
    public R<String> testQuartzUpdate(){
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setBeanName("testTask");
        scheduleJob.setJobId(100L);
        scheduleJob.setStatus(0);
        scheduleJob.setParams("修改-我是测试定时器");
        scheduleJob.setCronExpression("*/10 * * * * ?");
        scheduleJob.setRemark("修改-测试");
        scheduleJob.setCreateTime(new Date());
        Date updateTime = QuartzJobManager.updateScheduleJob(scheduleJob);
        return R.ok("ok：修改成功，时间，" + updateTime);
    }

    @GetMapping("/runjob")
    public R<String> testQuartzRunJob(){
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setBeanName("testTask");
        scheduleJob.setJobId(100L);
        scheduleJob.setStatus(0);
        scheduleJob.setParams("立即执行-我是测试定时器");
        scheduleJob.setCronExpression("*/2 * * * * ?");
        scheduleJob.setRemark("立即执行-测试");
        scheduleJob.setCreateTime(new Date());
        QuartzJobManager.run(scheduleJob);
        return R.ok("ok：立即执行成功");
    }

    @GetMapping("/pausejob")
    public R<String> testQuartzPauseJob(){
        QuartzJobManager.pauseJob(100L);
        return R.ok("ok：暂停成功");
    }

    @GetMapping("/resumejob")
    public R<String> testQuartzResumeJob(){
        QuartzJobManager.resumeJob(100L);
        return R.ok("ok：恢复成功");
    }

    @GetMapping("/delete")
    public R<String> testQuartzDelete(){
        QuartzJobManager.deleteScheduleJob(100L);
        return R.ok("ok：删除成功");
    }
}
